<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<button type="button">按钮1</button>
		<button type="button">按钮2</button>
		<button type="button">按钮3</button>
		<script type="text/javascript">
			
			//1.没有块级作用域引起的问题 for的块级
			//为什么闭包可以解决问题：函数是一个作用域.
			var btns=document.getElementsByTagName('button');
			for (var i = 0; i < btns.length; i++) {
					btns[i].addEventListener('click',function(){
						console.log('第'+i+'个按钮被点击');
					})
			} 
			//1.情况一：es5没有使用闭包(错误的方式)
			{
				var i=0;
				btns[i].addEventListener('click',function(){
					console.log('第'+i+'个按钮被点击');
				})
			}
			{
				var i=1;
				btns[i].addEventListener('click',function(){
					console.log('第'+i+'个按钮被点击');
				})
			}
			{
				var i=2;
				btns[i].addEventListener('click',function(){
					console.log('第'+i+'个按钮被点击');
				})
			}
			
			//2.情况二：es5中使用闭包
			var btns=document.getElementsByTagName('button');
			for (var i = 0; i < btns.length; i++) {
				(function(i){
					btns[i].addEventListener('click',function(){
						console.log('第'+i+'个按钮被点击');
					})
				})(i)
			} 
			
			function(i){ //i=0
					btns[i].addEventListener('click',function(){
						console.log('第'+i+'个按钮被点击');
					})
			}(0)
			function(i){ //i=1
					btns[i].addEventListener('click',function(){
						console.log('第'+i+'个按钮被点击');
					})
			}(1)
			function(i){ //i=2
					btns[i].addEventListener('click',function(){
						console.log('第'+i+'个按钮被点击');
					})
			}(2)
			
			//3.情况三：es6
			const btns=document.getElementsByTagName('button');
			for (let i = 0; i < btns.length; i++) {
					btns[i].addEventListener('click',function(){
						console.log('第'+i+'个按钮被点击');
					})
			} 
			{
				i=0;
				btns[i].addEventListener('click',function(){
					console.log('第'+i+'个按钮被点击');
				})
			}
			{
				i=1;
				btns[i].addEventListener('click',function(){
					console.log('第'+i+'个按钮被点击');
				})
			}
			{
				i=1;
				btns[i].addEventListener('click',function(){
					console.log('第'+i+'个按钮被点击');
				})
			}
		</script>
	</body>
</html>
